package jsu.xnm.evelyn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jsu.xnm.evelyn.bean.Dish;
import jsu.xnm.evelyn.bean.DishFlavor;
import jsu.xnm.evelyn.dto.DishDto;
import jsu.xnm.evelyn.mapper.DishMapper;
import jsu.xnm.evelyn.service.DishFlavorService;
import jsu.xnm.evelyn.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * @author xnm
 * @version 1.0
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;

    @Transactional
    @Override
    public void saveDishAndFlavor(DishDto dishDto) {
        //1.先保存菜品的基本信息到dish表
        dishDto.setCode(UUID.randomUUID().toString());//todo:设置菜品编码
        this.save(dishDto);
        //2.保存菜品口味到dish_flavor表
        Long dishId = dishDto.getId();//获取菜品id
        dishDto.getFlavors().forEach(flavor -> flavor.setDishId(dishId));//设置菜品id
        dishFlavorService.saveBatch(dishDto.getFlavors());//批量保存
    }

    @Override
    public DishDto getDishAndFlavorById(Long id) {
        //1.查询菜品基本信息
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);//将dish中的属性值复制到dishDto中

        //2.查询菜品口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        //3.将菜品信息和口味信息封装到DishDto中
        dishDto.setFlavors(flavors);
        dishDto.setCategoryName(dish.getName());//将对应id的dish name拷贝到dishDto中
        return dishDto;
    }

    @Transactional
    @Override
    public void updateDishAndFlavor(DishDto dishDto) {
        //1.更新菜品基本信息
        this.updateById(dishDto);
        //2.更新菜品口味信息
        //2.1删除当前菜品id对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //2.2保存新的口味信息
        dishDto.getFlavors().forEach(flavor ->  flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }
}
